# 根据已有模型自动标注图片生成标签
import os
import torch
from utils.torch_utils import select_device, time_sync
from models.common import DetectMultiBackend
from utils.general import (LOGGER, check_img_size, cv2, non_max_suppression, scale_coords)
from utils.dataloaders import LoadImages
from utils.plots import Annotator, colors

class SmartMa():
    def __init__(self):
        self.device = "cpu"
        self.model_path = "best.pt"
        self.imgs_path = "../tmp/images/"
        self.labels_save_path = "../tmp/labels/"
        self.model = self.model_load(weights=self.model_path, device=self.device)
        self.datalist = []
    # 模型初始化
    def model_load(self, weights="", device=''):
        device = select_device(device)
        model = DetectMultiBackend(weights, device=device, dnn=False)
        stride, names, pt, jit, onnx = model.stride, model.names, model.pt, model.jit, model.onnx
        if pt:
            model.model.float()
        print("模型加载完成")
        return model
    def genLabels(self):
        images = os.listdir(self.imgs_path)
        for img in images:
            img_path = self.imgs_path+img
            self.detect_img(img_path)
            # cv2.imshow("test", cv2.imread("tmp/single_result.jpg"))
            # cv2.waitKey(500)
            # cv2.destroyWindow("test")
            label_save_fname = self.labels_save_path+img.split(".")[0]+".txt"
            if len(self.datalist) != 0:
                fp = open(label_save_fname, mode="a")
                for item in self.datalist:
                    text = [str(i) for i in item]
                    fp.write(" ".join(text))
                    fp.write("\n")

    def detect_img(self, source):
        model = self.model
        imgsz = [640, 640]
        conf_thres = 0.35  # 置信度阈值
        iou_thres = 0.45
        max_det = 15  # 最大检测数量
        view_img = False
        save_crop = False
        nosave = False
        classes = None
        agnostic_nms = False
        augment = False
        visualize = False
        line_thickness = 1  # 线厚度 px
        hide_labels = False  # 隐藏标签
        hide_conf = False  # 隐藏置信度
        half = False
        print(source)
        if source == "":
            print("图片不存在")
        else:
            source = str(source)
            device = select_device(self.device)
            stride, names, pt, jit, onnx = model.stride, model.names, model.pt, model.jit, model.onnx
            imgsz = check_img_size(imgsz, s=stride)  # 图片尺寸检查
            save_img = not nosave and not source.endswith('.txt')
            dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt and not jit)
            dt, seen = [0.0, 0.0, 0.0], 0
            for path, im, im0s, vid_cap, s in dataset:
                oh, ow = im0s.shape[:2]
                t1 = time_sync()
                im = torch.from_numpy(im).to(device)
                im = im.half() if half else im.float()
                im /= 255
                if len(im.shape) == 3:
                    im = im[None]
                t2 = time_sync()
                dt[0] += t2 - t1
                pred = model(im, augment=augment, visualize=visualize)
                t3 = time_sync()
                dt[1] += t3 - t2
                pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
                dt[2] += time_sync() - t3
                self.datalist.clear()
                for i, det in enumerate(pred):
                    seen += 1
                    p, im0, frame = path, im0s.copy(), getattr(dataset, 'frame', 0)
                    s += '%gx%g ' % im.shape[2:]
                    annotator = Annotator(im0, line_width=line_thickness, example=str(names))
                    if len(det):
                        det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
                        for c in det[:, -1].unique():
                            n = (det[:, -1] == c).sum()
                            s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "
                        for *xyxy, conf, cls in reversed(det):
                            if save_img or save_crop or view_img:
                                c = int(cls)
                                label = None if hide_labels else (names[c] if hide_conf else f'{names[c]} {conf:.2f}')
                                print("data", xyxy, label)
                                x1, y1 = xyxy[:2]
                                x2, y2 = xyxy[2:]
                                x1, y1 = x1.item(), y1.item()
                                x2, y2 = x2.item(), y2.item()
                                xw, yh = x2-x1, y2-y1
                                cx, cy = x1+xw/2, y1+yh/2
                                self.datalist.append([c, cx/ow, cy/oh, xw/ow, yh/oh])
                                annotator.box_label(xyxy, label, color=colors(c, True))
                    LOGGER.info(f'{s}Done. ({t3 - t2:.3f}s)')
                    im0 = annotator.result()
                    cv2.imwrite("./tmp/single_result.jpg", im0)

if __name__ == '__main__':
    ai = SmartMa()
    ai.genLabels()